package com.wky.org.service.Impl;

import com.wky.basic.Result.PageResult;
import com.wky.basic.exception.BusinessException;
import com.wky.basic.service.impl.BaseServiceImpl;
import com.wky.basic.util.BaiduAuditUtils;
import com.wky.org.VO.ShopVO;
import com.wky.org.mapper.ShopAuditLogMapper;
import com.wky.org.mapper.ShopMapper;
import com.wky.org.mapper.EmployeeMapper;
import com.wky.org.pojo.Shop;
import com.wky.org.pojo.Employee;
import com.wky.org.pojo.ShopAuditLog;
import com.wky.org.service.EmployeeService;
import com.wky.org.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class ShopServicerImpl extends BaseServiceImpl<Shop> implements ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 店铺入驻
     * @param shop
     */
    @Override
    @Transactional
    public void shopRegister(Shop shop) {
        //校验
            //非空校验
        if (shop == null) {
            throw new BusinessException("参数不能为空");
        }

            //店铺名称是否重复，重复则不可入驻
        if (shop.getName() == null || shop.getName().trim().length() == 0) {
            throw new BusinessException("店铺名称不能为空");
        }
        Shop byName = shopMapper.findByName(shop.getName());
        if (byName != null) {
            throw new BusinessException("该店铺已入驻");
        }
            //每个店长只能管理一个店铺，可通过username判断员工是否存在，若存在再判断shop_id是否为空
        Employee employee = employeeMapper.findByUsername(shop.getAdmin().getUsername());
        if (employee != null) {
            if (employee.getShopId() != null) {
                throw new BusinessException("该店长已管理其他店铺");
            }
        }
            //判断两次密码是否一致
        if(!shop.getAdmin().getPassword().equals(shop.getAdmin().getConfirmPassword())){
            throw new BusinessException("两次密码不一致");
        }
            //店铺名称是否合法  @TODO 插眼
        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BusinessException("店铺名称不合法");
        }
        log.info("店铺名称合法");
            //店铺logo是否合法
        String logo = shop.getLogo();
        System.out.println("logo:"+logo);
        Boolean aBoolean = BaiduAuditUtils.ImgCensor(logo);
        if (!aBoolean){
            throw new BusinessException("店铺logo不合法");
        }
        log.info("店铺logo合法");


        //完成校验
        //设置注册时间
        shop.setRegisterTime(new Date());
        //设置店铺状态
        shop.setState(1);
        //新增店铺，并返回主键id
        shopMapper.add(shop);
        shop.getAdmin().setShopId(shop.getId());
        //若店长存在，则修改shop_id，否则新增店长
        if (employee != null) {
            employeeMapper.update(shop.getAdmin());
        }else{
            employeeService.add(shop.getAdmin());
        }
        //将店长id存入shop
        shop.setAdminId(shop.getAdmin().getId());
        //更新店铺
        shopMapper.update(shop);
    }

    /**
     * 店铺审核通过
     * @param shopAuditLog
     */
    @Override
    @Transactional
    public void shopAuditOk(ShopAuditLog shopAuditLog) {
        //修改店铺状态
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        //审核通过带激活
        shop.setState(2);
        shopMapper.update(shop);

        //添加店铺审核日志
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setState(2);
        //设置审核人id               @TODO
        shopAuditLogMapper.add(shopAuditLog);


        try {
            //发送激活邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //设置发送人
            mailMessage.setFrom("1721582950@qq.com");
            //邮件主题
            mailMessage.setSubject("请点击下面店铺激活链接");
            //邮件内容
            mailMessage.setText("http://localhost:8080/org/shop/shopActive?shopId="+shopAuditLog.getShopId());
            //收件人
            //根据shopId查询店铺，根据店铺id查询店长
            Shop shopById = shopMapper.findById(shopAuditLog.getShopId());
            Employee admin = employeeMapper.findById(shopById.getAdminId());
            mailMessage.setTo(admin.getEmail());
            javaMailSender.send(mailMessage);
        } catch (MailException e) {
            e.printStackTrace();
            throw new BusinessException("邮件发送失败,请确认邮箱是否正确！");
        }
    }

    /**
     * 店铺审核未通过
     * @param shopAuditLog
     */
    @Override
    @Transactional
    public void shopAuditNo(ShopAuditLog shopAuditLog) {
        //修改店铺状态
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(4);
        shopMapper.update(shop);

        //添加店铺审核日志
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setState(4);
        shopAuditLogMapper.add(shopAuditLog);
        try {
            //发送邮件
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom("1721582950@qq.com");
            mailMessage.setSubject("店铺入驻审核未通过");
            mailMessage.setText("店铺入驻审核未通过，请重新入驻");
            //收件人
            //根据shopId查询店铺，根据店铺id查询店长
            Shop shopById = shopMapper.findById(shopAuditLog.getShopId());
            Employee admin = employeeMapper.findById(shopById.getAdminId());
            mailMessage.setTo(admin.getEmail());
            javaMailSender.send(mailMessage);
        } catch (MailException e) {
            throw new BusinessException("邮件发送失败,请确认邮箱是否正确！");
        }
    }


    /**
     * 查询所有店铺
     */
    @Override
    public List<Shop> findAll() {
        List<Shop> shopList = shopMapper.findAll();
        for (Shop shop : shopList) {
            if (shop.getAdminId()!=null){
                shop.setAdmin(employeeMapper.findById(shop.getAdminId()));
            }
        }
        return shopList;
    }

    /**
     * 根据id查询店铺
     */
    @Override
    public Shop findById(Long id) {
        Shop shop = shopMapper.findById(id);
        if (shop.getAdminId()!=null){
            shop.setAdmin(employeeMapper.findById(shop.getAdminId()));
        }
        return shop;
    }

    /**
     * 店铺数据统计
     */
    @Override
    public Map<String, List<Integer>> chart() {
        //获取分组数据
        List<ShopVO> shopVOS = shopMapper.chart();
        //创建map
        Map<String,List<Integer>> map = new HashMap<>();
        map.put("x",shopVOS.stream().map(ShopVO::getState).toList());
        map.put("y",shopVOS.stream().map(ShopVO::getCount).toList());

        return map;
    }

    /**
     * 分页查询店铺
     */
    @Override
    public PageResult<Shop> findByPage(Shop shop) {
        List<Shop> shopList = shopMapper.findByPage(shop);
        for (Shop shop1 : shopList) {
            if (shop1.getAdminId()!=null){
                shop1.setAdmin(employeeMapper.findById(shop1.getAdminId()));
            }
        }
        return new PageResult<>(shopMapper.findTotal(shop),shopList);
    }


}
